package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.TransitionContext;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Function;
import com.walkline.util.network.MyConnectionFactory;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;
import com.walkline.zhihu.ZhihuSDK;
import com.walkline.zhihu.inf.SectionStories;
import com.walkline.zhihu.inf.SectionStory;

public class SectionDetailsScreen extends MainScreen
{
	ZhihuSDK _zhihu;
	private WorkQueue _queue = new WorkQueue(2);
	ForegroundManager _foreground = new ForegroundManager(0);
	ListStyleButtonSet _sectionSet = new ListStyleButtonSet();
	ListStyleButtonField _item;

	int _id;

	public SectionDetailsScreen(ZhihuSDK zhihu, String name, int id)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		setTitle("专题：" + name);

		_zhihu = zhihu;
		_id = id;

		add(_foreground);

		Function.attachTransition(this, TransitionContext.TRANSITION_FADE);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run() {getSectionStories();}
		});
	}

    private void getSectionStories()
    {
    	SectionStories sectionStories;
		RefreshStoriesScreen popupScreen = new RefreshStoriesScreen(_zhihu, String.valueOf(_id), RefreshActions.SECTIONSTORIES);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		sectionStories = popupScreen.getSectionStories();

		if (popupScreen != null) {popupScreen = null;}
		if (sectionStories != null)
		{
			refreshSection(sectionStories);
		}
    }

    private void refreshSection(SectionStories sectionStories)
    {
    	if (_sectionSet.getManager() == null) {_foreground.add(_sectionSet);}
		if (_sectionSet.getFieldCount() > 0) {_sectionSet.deleteAll();}

		Vector storiesVector = sectionStories.getStories();
		SectionStory sectionStory;

		for (int i=0; i<storiesVector.size(); i++)
		{
			sectionStory = (SectionStory) storiesVector.elementAt(i);
			if (sectionStory != null)
			{
				_item = new ListStyleButtonField(sectionStory);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {showStoryDetailScreen();}
					}
				});

				_sectionSet.add(_item);
			}
		}

		if (_sectionSet.getFieldCount() > 0)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {refreshListIcons();}
			});
		}
    }

    private void refreshListIcons()
    {
		ListStyleButtonField item;

		_queue.removeAll();

		for (int i=0; i<_sectionSet.getFieldCount(); i++)
		{
			Field object = _sectionSet.getField(i);

			if (object instanceof ListStyleButtonField)
			{
				item = (ListStyleButtonField) object;
				_queue.execute(new DownloadImages(item));
			}
		}
    }

    class DownloadImages implements Runnable
    {
    	ListStyleButtonField _item;
    	MyConnectionFactory _factory = new MyConnectionFactory();
    	HttpConnection _conn = null;
    	InputStream inputStream = null;

    	public DownloadImages(ListStyleButtonField item) {_item = item;}

		public void run()
		{
			if (_item.getThumbnailUrl().equalsIgnoreCase("")) {return;}

			ConnectionDescriptor connd = _factory.getConnection(_item.getThumbnailUrl());

			if (connd == null) {return;}

			try {
				_conn = (HttpConnection) connd.getConnection();
				_conn.setRequestProperty(HttpProtocolConstants.HEADER_CONNECTION, HttpProtocolConstants.HEADER_KEEP_ALIVE);

				inputStream = _conn.openInputStream();

				if (inputStream.available() > 0)
				{
					byte[] data = IOUtilities.streamToBytes(inputStream);

					if (data.length == _conn.getLength()) {_item.setThumbnail(data);}
				}

				inputStream.close();
			} catch (IOException e) {}
		}
	}

    private void showStoryDetailScreen()
    {
    	ListStyleButtonField item = (ListStyleButtonField) _sectionSet.getFieldWithFocus();

    	UiApplication.getUiApplication().pushScreen(new StoryDetailsScreen(_zhihu, item.getSectionStoryId(), RefreshActions.SECTIONSTORYDETAILS));
    }

    private void showExitDialog()
    {
		String[] yesno = {"是 (Y\u0332)", "否 (N\u0332)"};
		Dialog showDialog = new Dialog("确认退出知乎日报？", yesno, null, 0, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), USE_ALL_WIDTH);

		showDialog.doModal();
		if (showDialog.getSelectedValue() == 0) {System.exit(0);}
    }

    protected boolean keyChar(char character, int status, int time)
    {
    	switch (character)
    	{
			case Characters.LATIN_CAPITAL_LETTER_T:
			case Characters.LATIN_SMALL_LETTER_T:
				if (_sectionSet.getFieldCount() > 0) {_sectionSet.getField(0).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_B:
			case Characters.LATIN_SMALL_LETTER_B:
				if (_sectionSet.getFieldCount() > 0) {_sectionSet.getField(_sectionSet.getFieldCount()-1).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				showExitDialog();
				return true;
    	}

    	return super.keyChar(character, status, time);
    }
}